from support import Pet,Cat,Dog
from ensurepip import bootstrap
from flask import Flask,app,render_template,session,redirect,url_for,flash
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField,BooleanField,SelectField
from flask_sqlalchemy import SQLAlchemy

app=Flask(__name__)
app.config['SECRET_KEY']='test'
app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:123456@localhost/studentinfo'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True
bootstrap=Bootstrap(app)
db=SQLAlchemy(app)

class Major(db.Model):
    __tablename__ = 'majors'
    id = db.Column(db.Integer, primary_key=True)
    major_name = db.Column(db.String(100), unique=True, nullable=False)
    students = db.relationship('Basicinfo', backref='major', lazy='dynamic')
    def __repr__(self):
        return f'<Major {self.major_name}>'

class Basicinfo(db.Model):
    __tablename__='Basicinfo'
    id=db.Column(db.String(255),primary_key=True)
    studentName=db.Column(db.String(255))
    studentBirth=db.Column(db.String(255))
    isMale=db.Column(db.Boolean)
    major_id = db.Column(db.Integer, db.ForeignKey('majors.id'))

class NameForm(FlaskForm):
    id=StringField('请输入你的学号')
    studentName=StringField('请输入你的姓名')
    studentBirth=StringField('请输入你的出生日期')
    isMale=BooleanField('请选择你的性别')
    major = SelectField('请选择你的专业', coerce=int)
    submit=SubmitField('提交')

class EditForm(NameForm):
    submit = SubmitField("修改")

class DeleteForm(FlaskForm):
    submit = SubmitField("删除")

@app.route('/')
def index():
    studs = Basicinfo.query.all()
    majors = Major.query.all()
    return render_template('index.html',studs=studs,majors=majors)  

@app.route('/new',methods=['GET','POST'])
def new_stud():
    form=NameForm()
    form.major.choices = [(major.id, major.major_name) for major in Major.query.all()]
    if form.validate_on_submit():
        new_stud=Basicinfo(id=form.id.data,studentName=form.studentName.data,studentBirth=form.studentBirth.data,isMale=form.isMale.data,major_id=form.major.data)
        db.session.add(new_stud)
        db.session.commit()
        flash('学生信息添加成功！')
        return redirect(url_for('index'))
    return render_template('new.html',form=form)

@app.route("/edit/<string:id>",methods=["GET","POST"])
def edit_stud(id):
    form=EditForm()
    stud = Basicinfo.query.get(id)
    form.major.choices = [(major.id, major.major_name) for major in Major.query.all()]
    if form.validate_on_submit():
        stud.id=form.id.data
        stud.studentName=form.studentName.data
        stud.studentBirth=form.studentBirth.data
        stud.isMale=form.isMale.data
        stud.major = Major.query.get(form.major.data)
        db.session.commit()
        flash('学生信息修改成功！')
        return redirect(url_for('index'))
    form.id.data=stud.id
    form.studentName.data=stud.studentName
    form.studentBirth.data = stud.studentBirth
    form.isMale.data = stud.isMale
    if stud.major:
        form.major.data = stud.major.id
    return render_template('edit.html',form=form)

@app.route("/delete/<string:id>",methods=["GET","POST"])
def del_stud(id):
    stud = Basicinfo.query.get(id) 
    db.session.delete(stud)
    db.session.commit()
    flash('学生信息删除成功！')
    return redirect(url_for('index'))

@app.route("/major/<int:major_id>")
def filter_by_major(major_id):
    major = Major.query.get_or_404(major_id)
    studs = major.students.all()
    majors = Major.query.all() 
    return render_template('index.html', studs=studs, majors=majors)

@app.route('/testvariables')
def testvariables():
    aCat = Cat("苏新皓",2,10,"baby Cat")
    aDog = Dog("Bad Dog",2,10,"Bad Dog")
    aCat.shout()
    aDog.shout()
    return render_template('testvariables.html',aCat = aCat,aDog = aDog)

@app.route('/user',methods=['GET','POST'])
def user():
    studentName=None
    form=NameForm()
    if form.validate_on_submit():
        oldname=session.get('studentName')
        if oldname is not None and oldname!=form.studentName.data:
            flash('您的姓名已经更新成功！')
            session['studentName']=form.studentName.data
        return redirect(url_for('user'))
    return render_template('user.html',form=form,studentName=session.get('studentName'))        
 
@app.route('/<username>')
def test2(username):
    return render_template('test2.html',username=username)

@app.route('/hello/<name>')
def hello(name):
    comments=['你好1','你好2','你好3']
    return render_template('user.html',name1=name,comments=comments,form=NameForm())

if __name__=='__main__':
    app.run(debug=True)